define([
    'jquery',
    'underscore',
    'backbone',
    'text!template/sandbox/file_create.html',
    'bootstrap'
], function(
    $,
    _,
    Backbone,
    CreateTemplate,
    require
){

    var App = Backbone.View.extend({
        el: '#page-sandbox',
        template: _.template(CreateTemplate),

        initialize: function() {
            this.render();
            this.autoUpload();
            this.dropzoneHeight();

            // Call upload initialization file
            if (window.File && window.FileList && window.FileReader) {
                this.uploadInit();
            }
        },

        render: function() {
        },

        autoUpload: function() {
            $(".dev_hidden_upload").change(function() {
                $("#dev_auto_upload").submit();
            });
        },

        uploadInit: function() {
            var _this = this;
            var filedrag = document.getElementById("dev_dropzone");

            // detect xhr2 available
            var xhr = new XMLHttpRequest();
            if (xhr.upload) {
                // file drop
                filedrag.addEventListener("dragover", FileDragHover, false);
                filedrag.addEventListener("dragleave", FileDragLeave, false);
                filedrag.addEventListener("drop", FileSelectHandler, false);
            }

            // File drag hover
            function FileDragHover(e) {
                e.stopPropagation();
                e.preventDefault();
                var _extraClass = (e.type == "dragover" ? "hover" : "");
                $(e.target).addClass(_extraClass);
            }

            // File drag leave
            function FileDragLeave(e) {
                var _this = $(e.target);
                if (_this.hasClass('hover')) {
                    _this.removeClass('hover');
                }
            }

            // File select handler
            function FileSelectHandler(e) {
                var _time = new Date();
                var _timeNow = _time.getFullYear().toString() + '/' + ("0" + (_time.getMonth()+1)).slice(-2) + '/' + _time.getDate() + ' ' + _time.getHours() + ':' + _time.getMinutes();
                var _timeStamp = _time.getTime();

                e.preventDefault();
                // cancel event and hover style
                FileDragLeave(e);

                // fetch file object
                var files = e.target.files || e.dataTransfer.files;
                for (var i=0, f; f=files[i]; i++) {
                    RenderFileTemplate(f, _timeNow, _timeStamp);
                    UploadFile(f, _timeStamp);
                }
            }

            // Render file template
            function RenderFileTemplate(file, timeNow, timeStamp) {
                _this.$el.find('[bb-sandbox-container]').append(
                    _this.template({
                        name: file.name,
                        time: timeNow,
                        size: _this.formatter(file.size),
                        flag: timeStamp
                    })
                );
            }

            function UploadFile(file, flag) {
                var _form = new FormData();
                _form.append('fill', file);
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '/sandbox/upload', true);
                xhr.overrideMimeType("application/octet-stream");

                // Progress
                xhr.onprogress = UpdateProgress(flag);
                xhr.upload.onprogress = UpdateProgress(flag);

                // Upload complete
                xhr.onload = function(e) {
                    if (this.status == 200) {
                        var selector = '#flag' + flag;
                        $(selector).find('.prog').hide();
                    }
                };

                xhr.send(_form);
            }

            // Update upload progress percents
            function UpdateProgress(flag) {
                return function(e) {
                    var selector = '#flag' + flag;
                    var _progress = $(selector).find('.prog');
                    if (e.lengthComputable) {
                        var _value = (e.loaded / e.total) * 100 + '%';
                        _progress.css("width", _value);
                    }
                };
            }

        },

        dropzoneHeight: function() {
            var pageHeight = $(document).height();
            var topbarHeight = $('.elu-topbar').height();
            var pageHeaderHeight = $('.elu-wrapper .elu-content').height();
            var pageHeaderMT = $('.elu-wrapper .elu-content').css("marginTop").split('px')[0];
            var pageHeaderMB = $('.elu-wrapper .elu-content').css("marginBottom").split('px')[0];
            var result = pageHeight - topbarHeight - pageHeaderHeight - pageHeaderMB - pageHeaderMT;
            $("#dev_dropzone").css("height", result);
        },

        formatter: function(mag) {
            var i = -1;
            var byteUnits = ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            do { mag = mag / 1000; i++; } while (mag > 1000);
            return Math.max(mag, 0.1).toFixed(1) + byteUnits[i];
        }

    });

    new App();
});
